package com.uls.web.controller.hdh;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.uls.common.core.domain.entity.SysUser;
import com.uls.common.utils.SecurityUtils;
import com.uls.framework.config.MinioProp;
import com.uls.framework.utils.MinioUtils;
import com.uls.hdh.domain.HdhUserWeights;
import com.uls.hdh.service.IHdhUserWeightsService;
import com.uls.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.uls.common.annotation.Log;
import com.uls.common.core.controller.BaseController;
import com.uls.common.core.domain.AjaxResult;
import com.uls.common.enums.BusinessType;
import com.uls.hdh.domain.HdhUsers;
import com.uls.hdh.service.IHdhUsersService;
import com.uls.common.utils.poi.ExcelUtil;
import com.uls.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户Controller
 * 
 * @author hdh
 * @date 2024-11-11
 */
@RestController
@RequestMapping("/hdh/users")
public class HdhUsersController extends BaseController
{
    @Autowired
    private IHdhUsersService hdhUsersService;
    @Autowired
    private IHdhUserWeightsService hdhUserWeightsService;
    @Autowired
    private MinioUtils minioUtils;


    @Autowired
    private MinioProp minioProp;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('hdh:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(HdhUsers hdhUsers)
    {
        startPage();
        List<HdhUsers> list = hdhUsersService.selectHdhUsersList(hdhUsers);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('hdh:users:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HdhUsers hdhUsers)
    {
        List<HdhUsers> list = hdhUsersService.selectHdhUsersList(hdhUsers);
        ExcelUtil<HdhUsers> util = new ExcelUtil<HdhUsers>(HdhUsers.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('hdh:users:query')")
    @GetMapping(value = "/{usersId}")
    public AjaxResult getInfo(@PathVariable("usersId") Long usersId)
    {
        return success(hdhUsersService.selectHdhUsersByUsersId(usersId));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('hdh:users:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HdhUsers hdhUsers)
    {
        hdhUsers.setCreatedBy(this.getUsername());
        hdhUsers.setCreatedTime(new Date());
        SysUser sysUser = new SysUser();
        sysUser.setAvatar(hdhUsers.getPicture());
        Long[] roleIds = new Long[0];
        Integer dictionary=Integer.parseInt(hdhUsers.getPosition());
        switch (dictionary){
            case 0:
                roleIds = new Long[]{101L};
                break;
            case 1:
                roleIds = new Long[]{102L};
                break;
            case 2:
                roleIds = new Long[]{103L};
                break;
            case 3:
                roleIds = new Long[]{104L};
                break;
            case 4:
                roleIds = new Long[]{105L};
                break;
        }
        sysUser.setRoleIds(roleIds);
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyMMddHHmmss");
        Long number = Long.parseLong(format.format(date));
        hdhUsers.setUsernumber(number);
        sysUser.setUserName(String.valueOf(hdhUsers.getUsernumber()));
        sysUser.setNickName(hdhUsers.getUsername());
        sysUser.setPassword("admin123");
        sysUser.setCreateBy(this.getUsername());
        sysUser.setCreateTime(new Date());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        userService.insertUser(sysUser);

        hdhUsersService.insertHdhUsers(hdhUsers);
        HdhUserWeights hdhUserWeights = new HdhUserWeights();
        hdhUserWeights.setUsersId(hdhUsers.getUsersId());
        switch (dictionary) {
            case 0:
                hdhUserWeights.setWeightFactor(1);
                break;
            case 1:
                hdhUserWeights.setWeightFactor(2);
                break;
            case 2:
                hdhUserWeights.setWeightFactor(3);
                break;
            case 3:
                hdhUserWeights.setWeightFactor(4);
                break;
            default:
                hdhUserWeights.setWeightFactor(0);
                break;
        }
        hdhUserWeights.setCreatedBy(this.getUsername());
        hdhUserWeights.setCreatedTime(new Date());
        hdhUserWeightsService.insertHdhUserWeights(hdhUserWeights);

        return toAjax(true);
        //return toAjax(hdhUsersService.insertHdhUsers(hdhUsers));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('hdh:users:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HdhUsers hdhUsers)
    {
        hdhUsers.setUpdatedBy(this.getUsername());
        hdhUsers.setUpdatedTime(new Date());
        SysUser sysUser = userService.selectUserByUserName(String.valueOf(hdhUsers.getUsernumber()));
        Long[] roleIds = new Long[0];
        Integer dictionary=Integer.parseInt(hdhUsers.getPosition());
        switch (dictionary){
            case 0:
                roleIds = new Long[]{101L};
                break;
            case 1:
                roleIds = new Long[]{102L};
                break;
            case 2:
                roleIds = new Long[]{103L};
                break;
            case 3:
                roleIds = new Long[]{104L};
                break;
            case 4:
                roleIds = new Long[]{105L};
                break;
        }
        sysUser.setRoleIds(roleIds);
        HdhUserWeights hdhUserWeights=hdhUserWeightsService.selectHdhUserWeightsByUsersId(hdhUsers.getUsersId());
        switch (dictionary){
            case 0:
                hdhUserWeights.setWeightFactor(1);
                break;
            case 1:
                hdhUserWeights.setWeightFactor(2);
                break;
            case 2:
                hdhUserWeights.setWeightFactor(3);
                break;
            case 3:
                hdhUserWeights.setWeightFactor(4);
                break;
            default:
                hdhUserWeights.setWeightFactor(0);
                break;
        }
        hdhUserWeights.setUpdatedBy(this.getUsername());
        hdhUserWeights.setUpdatedTime(new Date());
        hdhUserWeightsService.updateHdhUserWeights(hdhUserWeights);
        sysUser.setAvatar(hdhUsers.getPicture());
        sysUser.setNickName(hdhUsers.getUsername());
        sysUser.setUpdateBy(this.getUsername());
        sysUser.setUpdateTime(new Date());
        userService.updateUser(sysUser);
        return toAjax(hdhUsersService.updateHdhUsers(hdhUsers));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('hdh:users:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{usersIds}")
    public AjaxResult remove(@PathVariable Long[] usersIds)
    {
        for(Long id:usersIds){
            HdhUsers hdhUsers=hdhUsersService.selectHdhUsersByUsersId(id);
            SysUser sysUser = userService.selectUserByUserName(String.valueOf(hdhUsers.getUsernumber()));
            userService.deleteUserById(sysUser.getUserId());
            HdhUserWeights hdhUserWeights=hdhUserWeightsService.selectHdhUserWeightsByUsersId(id);
            hdhUserWeightsService.deleteHdhUserWeightsByUserWeightId(hdhUserWeights.getUserWeightId());
        }
        return toAjax(hdhUsersService.deleteHdhUsersByUsersIds(usersIds));
    }

    /**
     * 上传头像图片
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
        JSONObject res = null;
        try {
            res = minioUtils.uploadFile(file, minioProp.getBucket());
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }
}
